package cn.yyd.org.service.impl;

import cn.yyd.basic.exception.BusinessException;
import cn.yyd.org.domain.Employee;
import cn.yyd.org.domain.Shop;
import cn.yyd.org.mapper.EmployeeMapper;
import cn.yyd.org.mapper.ShopMapper;
import cn.yyd.org.service.IShopService;
import cn.yyd.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
    * @Title: settlement
    * @Description: 店铺入驻方法
    * @Author: Mr.She
    * @Version: 1.0
    * @Date:  2022/7/1 14:10
    * @Parameters: [shop]
    * @Return void
    */
    @Override
    public void settlement(Shop shop) {
        if (StringUtils.isEmpty(shop.getName())){
            throw new RuntimeException("店铺名称不能为空，请重新输入！！！");
        }
        Shop loadShop = shopMapper.loadByName(shop.getName());
        if (loadShop != null ){
            throw new RuntimeException("店铺已经被注册,请重新输入");
        }
        // 判断管理人员是否已经注册并且已经注册了店铺
        Employee admin = shop.getAdmin();
        Employee loadEmp = employeeMapper.loadByUserName(admin.getUsername());
        // 判断管理员和店铺是否存在
        if (loadEmp != null && loadEmp.getShopId() != null){
            throw new RuntimeException("该管理员已经绑定了店铺,请重新输入！");
        }
        // 判断管理员是否存在，不存在则添加保存起来
        if (loadEmp == null){
            employeeMapper.save(admin);
        }
        // 保存店铺信息
        shop.setAdminId(admin.getId());
        shopMapper.save(shop);
        // 修改管理人员所属的店铺信息
        admin.setShopId(shop.getId());
        employeeMapper.update(admin);
    }
}
